package cn.socialcredits.activity.business

import javax.inject.Singleton

import akka.actor.{Actor, Props}
import cn.socialcredits.activity.setting.Settings
import com.typesafe.scalalogging.StrictLogging
import org.apache.commons.mail.{DefaultAuthenticator, SimpleEmail}
import play.api.Play.current
import play.api.libs.concurrent.Akka

/**
 * 邮件服务
 * Created by jingyang on 15/7/29.
 */
@Singleton
class EmailService {
  private val emailSenderActor = Akka.system.actorOf(Props[EmailServiceActor], "email-sender")

  def sendEmail(id: String, subject: String, content: String): Unit = {
    emailSenderActor ! SendEmail(id, subject, content)
  }
}

class EmailServiceActor extends Actor with StrictLogging {
  override def receive: Receive = {
    case SendEmail(id, subject, content) =>
      val email = new SimpleEmail()
      email.setHostName(Settings.email.hostName)
      email.setSmtpPort(Settings.email.portSsl)
      email.setSSLOnConnect(true)
      email.setAuthenticator(new DefaultAuthenticator(Settings.email.username, Settings.email.password))
      email.setFrom(Settings.email.from)
      email.setSubject(subject)
      email.setMsg(content)
      email.addTo(Settings.email.to: _*)
      logger.info(
        s"""id: $id
            |from: ${Settings.email.from}
            |to: ${Settings.email.to}
            |$subject
            |$content""".stripMargin)
      val result = email.send()
      logger.info(
        s"""id: $id
            |[result] $result""".stripMargin)
  }
}

case class SendEmail(id: String, subject: String, content: String)
